package com.cbs.android.module.discussion.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.cbs.android.component.application.activity.CBSActivity;
import com.cbs.android.component.application.activity.delayedtask.DelayedTask;
import com.cbs.android.component.application.activity.handler.CBSSimpleActivityResultHandler;
import com.cbs.android.component.applicationutils.Global;
import com.cbs.android.component.log.L;
import com.cbs.android.component.network.HttpClient;
import com.cbs.android.component.network.Request;
import com.cbs.android.component.network.Response;
import com.cbs.android.component.network.ResponseHandler;
import com.cbs.android.component.network.SimpleResponseHandler;
import com.cbs.android.component.network.decoder.GsonDecoder;
import com.cbs.android.component.share.shareinterface.ShareHandler;
import com.cbs.android.component.share.shareinterface.constant.SharePlatform;
import com.cbs.android.component.share.shareinterface.entity.ShareMessage;
import com.cbs.android.component.toast.Toast;
import com.cbs.android.extension.glide.target.RoundedImageViewTarget;
import com.cbs.android.extension.glide.urlloader.qiniu.QiniuUrlLoader;
import com.cbs.android.extension.glide.urlloader.qiniu.url.AvatarUrl;
import com.cbs.android.extension.recyclerviewadapter.RecyclerViewAdapter;
import com.cbs.android.module.discussion.DiscussionModule;
import com.cbs.android.module.discussion.R;
import com.cbs.android.module.discussion.entity.Comment;
import com.cbs.android.module.discussion.entity.CommentSnapshot;
import com.cbs.android.module.discussion.entity.SubjectSnapshot;
import com.cbs.android.module.discussion.utils.Constants;
import com.cbs.android.module.user.network.CBSUserRequest;
import com.cbs.android.module.user.user.UserModule;
import com.cbs.android.module.user.user.entity.User;
import com.cbs.android.module.userkit.UserKit;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.List;

import cn.bingoogolapple.refreshlayout.BGANormalRefreshViewHolder;
import cn.bingoogolapple.refreshlayout.BGARefreshLayout;
import okhttp3.CacheControl;

/**
 * Created by broche on 5/18/16.
 */
public abstract class DiscussionSummaryActivity<Subject> extends CBSActivity implements View.OnClickListener {
    private static final String TAG = DiscussionSummaryActivity.class.getName();
    private static final String CommentsUrlTpl = "social/api/v1/forums/%d/subjects/%d/comments";
    private static final String CommentsTopUrlTpl = "social/api/v1/forums/%d/subjects/%d/comments/top?pageno=0&pagesize=5&replycount=%d";

    protected abstract int getForumId();

    protected abstract Class<? extends DiscussionListActivity> getListActivityClass();

    protected abstract Subject onGetData(Context context, int subjectId);

    protected abstract View onCreateView(Context context, ViewGroup viewGroup);

    protected abstract void onBindView(Context context, View view, Subject data);

    protected abstract SubjectSnapshot onSnapshot(Context context, Subject subject);

    protected abstract ShareMessage onShare(Context context, int subjectId);

    protected Class<? extends CommentAddActivity> getCommentAddActivityClass() {
        return CommentAddActivity.class;
    }

    private HttpClient httpClient = Global.getHttpClient().clone();
    private RefreshFinishTask refreshFinishTask = new RefreshFinishTask();

    private int subjectId = -1;
    private List<Comment> commentsTop = new ArrayList<>();
    private Subject subjectObject = null;

    private View subjectView = null;
    private BGARefreshLayout refreshView = null;
    private RecyclerView contentView;
    private TextView commentCountView = null;

    private MyAdapter myAdapter = new MyAdapter();

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.cbs_discussion_summary);

        Intent intent = getIntent();
        subjectId = intent.getIntExtra(Constants.SubjectId, -1);

        if (subjectId < 0) {
            Toast.show(getString(R.string.cbs_discussion_hint_paramerror));
            finish();
            return;
        }

        httpClient.setDebug(DiscussionModule.isDebug());

        refreshView = (BGARefreshLayout) findViewById(R.id.cbs_discussion_summary_refresh);
        contentView = (RecyclerView) findViewById(R.id.cbs_discussion_summary_content);
        contentView.setLayoutManager(new LinearLayoutManager(this));
        commentCountView = (TextView) findViewById(R.id.cbs_discussion_summary_commentcount);
        subjectView = onCreateView(this, contentView);
        View emptyView = getLayoutInflater().inflate(R.layout.cbs_discussion_emptycomment, contentView, false);

        myAdapter.setHeaderView(subjectView);
        myAdapter.setEmptyView(emptyView);

        contentView.setAdapter(myAdapter);
        refreshView.setRefreshViewHolder(new BGANormalRefreshViewHolder(this, true));
        refreshView.setDelegate(new MyDelegate());

        findViewById(R.id.cbs_discussion_summary_back).setOnClickListener(this);
        findViewById(R.id.cbs_discussion_summary_comment).setOnClickListener(this);
        findViewById(R.id.cbs_discussion_summary_commentcountcontainer).setOnClickListener(this);
        findViewById(R.id.cbs_discussion_summary_share).setOnClickListener(this);

        refreshView.beginRefreshing();
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.cbs_discussion_summary_back) {
            finish();
        } else if (v.getId() == R.id.cbs_discussion_summary_comment) {
            if (UserModule.getUser() == null) {
                UserKit.login(DiscussionSummaryActivity.this, new CBSSimpleActivityResultHandler() {
                    @Override
                    public void onSuccess(int requestCode, Intent data) {
                        Toast.show(getString(R.string.cbs_discussion_hint_loginsuccess));
                    }

                    @Override
                    public void onCancel(int requestCode, Intent data) {
                        Toast.show(getString(R.string.cbs_discussion_hint_logincanceled));
                    }
                });
                return;
            }
            if (subjectObject == null) {
                Toast.show(getString(R.string.cbs_discussion_hint_dataloading));
                return;
            }
            SubjectSnapshot subjectSnapshot = onSnapshot(DiscussionSummaryActivity.this, subjectObject);

            User user = UserModule.getUser();
            CommentSnapshot commentSnapshot = new CommentSnapshot()
                    .setSenderid(user.getId()).setSendernickname(user.getNickName())
                    .setSenderavatar(user.getAvatar()).setSendersex(user.getSex())
                    .setSubjectid(subjectId);
            Gson gson = new Gson();
            String commentSnapshotStr = gson.toJson(commentSnapshot);
            String subjectSnapshotStr = gson.toJson(subjectSnapshot);

            Intent intent = new Intent(DiscussionSummaryActivity.this, getCommentAddActivityClass());
            intent.putExtra(Constants.ForumId, getForumId());
            intent.putExtra(Constants.SubjectId, subjectId);
            intent.putExtra(Constants.SubjectSnapshot, subjectSnapshotStr);
            intent.putExtra(Constants.CommentSnapshot, commentSnapshotStr);
            startActivityForResult(intent, 0, R.anim.cbs_slide_in_bottom, 0);
        } else if (v.getId() == R.id.cbs_discussion_summary_commentcountcontainer) {
            Intent intent = new Intent(DiscussionSummaryActivity.this, getListActivityClass());
            intent.putExtra(Constants.SubjectId, subjectId);
            startActivityForResult(intent, 0);
        } else if (v.getId() == R.id.cbs_discussion_summary_share) {
            if (DiscussionModule.getShareService() != null) {
                ShareMessage shareMessage = onShare(DiscussionSummaryActivity.this, subjectId);
                if (shareMessage == null) {
                    Toast.show(getString(R.string.cbs_discussion_hint_dataloading));
                } else {
                    DiscussionModule.getShareService().share(DiscussionSummaryActivity.this, SharePlatform.QQ | SharePlatform.QZone | SharePlatform.Wechat | SharePlatform.WechatMoments, shareMessage, new ShareHandler() {
                        @Override
                        public void onSuccess() {
                            Toast.show(getString(R.string.cbs_discussion_hint_sharesuccess));
                        }

                        @Override
                        public void onException(Exception e) {
                            L.e(TAG, "share exception", e);
                            Toast.show(getString(R.string.cbs_discussion_hint_sharefailure));
                        }

                        @Override
                        public void onFailure(int i, String s) {
                            L.e(TAG, String.format("code: %d\tmessage: %s", i, s));
                            Toast.show(getString(R.string.cbs_discussion_hint_sharefailure));
                        }
                    });
                }
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0) {
            if (resultCode == RESULT_OK) {
                refreshView.beginRefreshing();
            }
        }
    }

    private void onRefreshFinish(int action) {
        Bundle bundle = new Bundle();
        bundle.putInt("action", action);
        doDelayed(refreshFinishTask, bundle);
    }

    private class RefreshFinishTask implements DelayedTask {
        private int refreshCounter = 0;

        @Override
        public void doDelayed(Bundle data) {
            int action = data.getInt("action");
            if (action == 0) {
                refreshCounter = 0;
            } else {
                refreshCounter++;
                if (refreshCounter >= 2) {
                    refreshView.endRefreshing();
                }
            }
        }
    }

    private class MyDelegate implements BGARefreshLayout.BGARefreshLayoutDelegate {
        @Override
        public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout bgaRefreshLayout) {
            onRefreshFinish(0);

            Request requestCommentsTop = new CBSUserRequest(String.format(Global.getServerHost() + "/" + CommentsTopUrlTpl, getForumId(), subjectId, 0))
                    .setDecoder(new GsonDecoder(new TypeToken<List<Comment>>() {
                    }.getType()))
                    .cacheControl(CacheControl.FORCE_NETWORK)
                    .setResponseHandler(new SimpleResponseHandler<List<Comment>>() {
                        @Override
                        public void onSuccess(List<Comment> entity) {
                            DiscussionSummaryActivity.this.commentsTop.clear();
                            DiscussionSummaryActivity.this.commentsTop.addAll(entity);
                            myAdapter.notifyDataSetChanged();

                            onRefreshFinish(1);
                        }

                        @Override
                        public void onFailure(int code, String message) {
                            Toast.show(getString(R.string.cbs_discussion_hint_loadfailure));
                            onRefreshFinish(1);
                        }

                        @Override
                        public void onException(Request request, Exception e) {
                            super.onException(request, e);
                            onRefreshFinish(1);
                        }
                    });
            httpClient.send(requestCommentsTop);

            Request requestComments = new CBSUserRequest(String.format(Global.getServerHost() + "/" + CommentsUrlTpl, getForumId(), subjectId))
                    .head()
                    .cacheControl(CacheControl.FORCE_NETWORK)
                    .setResponseHandler(new ResponseHandler() {
                        @Override
                        public void onResponse(Response response) {
                            if (response.isSuccessful()) {
                                String countStr = response.getHeader("count");
                                commentCountView.setText(countStr);
                            } else {
                                // do nothing
                            }
                        }

                        @Override
                        public void onException(Request request, Exception e) {
                            // do nothing
                        }
                    });
            httpClient.send(requestComments);

            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    subjectObject = onGetData(DiscussionSummaryActivity.this, subjectId);
                    doDelayed(new DelayedTask() {
                        @Override
                        public void doDelayed(Bundle data) {
                            myAdapter.notifyDataSetChanged();
                            onBindView(DiscussionSummaryActivity.this, subjectView, subjectObject);
                            onRefreshFinish(1);
                        }
                    });
                }
            });
            thread.start();
        }

        @Override
        public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout bgaRefreshLayout) {
            return false;
        }
    }

    private class MyAdapter extends RecyclerViewAdapter {
        private static final int Section = 0;
        private static final int Item = 1;

        @Override
        protected RecyclerView.ViewHolder onCreateContentViewHolder(ViewGroup parent, int viewType) {
            RecyclerView.ViewHolder viewHolder;
            if (viewType == Section) {
                View view = getLayoutInflater().inflate(R.layout.cbs_discussion_list_section, parent, false);
                viewHolder = new SectionViewHolder(view);
            } else {
                View view = getLayoutInflater().inflate(R.layout.cbs_discussion_summary_item, parent, false);
                viewHolder = new ItemViewHolder(view);
            }
            return viewHolder;
        }

        @Override
        protected void onBindContentViewHolder(RecyclerView.ViewHolder holder, int position) {
            int viewType = getContentViewType(position);
            if (viewType == Section) {
                // do nothing
            } else {
                Comment comment = commentsTop.get(position - 1);
                ItemViewHolder itemViewHolder = (ItemViewHolder) holder;

                Glide.with(DiscussionSummaryActivity.this)
                        .using(new QiniuUrlLoader(DiscussionSummaryActivity.this))
                        .load(new AvatarUrl(DiscussionModule.getAvatarPath(comment.getSenderAvatar())))
                        .asBitmap()
                        .placeholder(R.drawable.cbs_discussion_avatar)
                        .error(R.drawable.cbs_discussion_avatar)
                        .into(new RoundedImageViewTarget(itemViewHolder.senderAvatarView));
                itemViewHolder.senderNicknameView.setText(comment.getSenderNickName());
                itemViewHolder.senderSexView.setImageResource(comment.getSenderSex() == 0 ? R.drawable.cbs_discussion_sex_female_default : R.drawable.cbs_discussion_sex_male_default);
                itemViewHolder.timestampView.setText(DiscussionModule.getDateFormatter().format(comment.getTimestamp()));
                itemViewHolder.starCountView.setText(comment.getStarCount() + "");
                itemViewHolder.contentView.setText(comment.getContent());
            }
        }

        @Override
        public int getContentCount() {
            if (commentsTop.size() > 0) {
                return commentsTop.size() + 1;
            } else {
                return 0;
            }
        }

        @Override
        protected int getContentViewType(int position) {
            if (position == 0) {
                return Section;
            } else {
                return Item;
            }
        }

        private class SectionViewHolder extends RecyclerView.ViewHolder {
            public SectionViewHolder(View itemView) {
                super(itemView);
            }
        }

        private class ItemViewHolder extends RecyclerView.ViewHolder {
            private ImageView senderAvatarView;
            private TextView senderNicknameView;
            private ImageView senderSexView;
            private TextView timestampView;
            private TextView starCountView;
            private TextView contentView;

            public ItemViewHolder(View itemView) {
                super(itemView);

                itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(DiscussionSummaryActivity.this, getListActivityClass());
                        intent.putExtra(Constants.SubjectId, subjectId);
                        startActivityForResult(intent, 0);
                    }
                });

                senderAvatarView = (ImageView) itemView.findViewById(R.id.cbs_discussion_summary_item_senderavatar);
                senderNicknameView = (TextView) itemView.findViewById(R.id.cbs_discussion_summary_item_sendernickname);
                senderSexView = (ImageView) itemView.findViewById(R.id.cbs_discussion_summary_item_sendersex);
                timestampView = (TextView) itemView.findViewById(R.id.cbs_discussion_summary_item_timestamp);
                starCountView = (TextView) itemView.findViewById(R.id.cbs_discussion_summary_item_starcount);
                contentView = (TextView) itemView.findViewById(R.id.cbs_discussion_summary_item_content);
            }
        }
    }

    protected void setTitle(String title) {
        TextView titleView = (TextView) findViewById(R.id.cbs_discussion_summary_title);
        titleView.setText(title);
    }
}
